package MypageController.MyComment;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import Connect.connector;

public class MyCommentDAO{
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	public void commentWrite(MyCommentBean mycommentbean){
		conn = connector.getConnection();
		try{
			
			String sql = "INSERT INTO COMMENTBLOGS (`Blogs_Id`, `Entries_Id`, `Cblog_Nick`, `Cblog_Date`, `Cblog_Contents`) VALUES (?, ?, ?, Sysdate(), ?)";
			
			pstmt = conn.prepareStatement( sql );
			
			pstmt.setInt(1, mycommentbean.getBlogs_Id());
			pstmt.setInt(2, mycommentbean.getEntries_Id());
			pstmt.setString(3, mycommentbean.getCblog_Nick());
			pstmt.setString(4, mycommentbean.getCblog_Contents());

			pstmt.executeUpdate();
			
		}catch(Exception e){
			 e.printStackTrace();
		}finally{
			connector.releaseConnection(conn, pstmt, rs);
		}

	}
	
	public void commentDelet(int commentid){
		conn = connector.getConnection();
		try{
			
			
			String sql = "DELETE FROM `COMMENTBLOGS` WHERE (`ID`=?)";
			
			pstmt = conn.prepareStatement( sql );
			
			pstmt.setInt(1, commentid);

			pstmt.executeUpdate();
			
		}catch(Exception e){
			 e.printStackTrace();
		}finally{
			connector.releaseConnection(conn, pstmt, rs);
		}
	}
	public MyCommentBean[] commentGet (int entriesid){
		conn = connector.getConnection();
		ArrayList<MyCommentBean> result = new ArrayList<MyCommentBean>();
		try{
			
			
			String sql = "select * from COMMENTBLOGS where Entries_Id = ? ORDER BY `Cblog_Date` DESC";
			
			pstmt = conn.prepareStatement( sql );
			
			pstmt.setInt(1, entriesid);
			
			rs = pstmt.executeQuery();
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			
			while( rs.next()){
				MyCommentBean mcbean = new MyCommentBean();
				mcbean.setID(rs.getInt("ID"));
				mcbean.setEntries_Id(rs.getInt("Entries_Id"));
				mcbean.setCblog_Nick(rs.getString("Cblog_Nick"));
				mcbean.setCblog_Date(sdf.format(rs.getTimestamp("Cblog_Date")));
				mcbean.setCblog_Contents(rs.getString("Cblog_Contents"));
				result.add(mcbean);
			}
			
		}catch(Exception e){
			 e.printStackTrace();
		}finally{
			connector.releaseConnection(conn, pstmt, rs);
		}
		return result.toArray(new MyCommentBean[0]);
	}
	
	public int commentCountGet (int entriesid){	
		conn = connector.getConnection();
		try{
			
			String sql = "select count(*) from COMMENTBLOGS where Entries_Id = ?";
			
			pstmt = conn.prepareStatement( sql );
			
			pstmt.setInt(1, entriesid);
			
			rs = pstmt.executeQuery();
			
			if( rs.next()){
				int count = rs.getInt("count(*)");		
				return count;
			}
		}catch(Exception e){
			 e.printStackTrace();
		}finally{
			connector.releaseConnection(conn, pstmt, rs);
		}
		return 0;
	}
}
